import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.yc.entity.Cartoon;
import com.yc.entity.Pmap;
import com.yc.entity.User;
import com.yc.index.web.IndexAction;
import com.yc.index.web.ResourceAction;
import com.yc.index.web.UserAction;
import com.yc.util.DateUtil;
import com.yc.util.FileUtil;
import com.yc.util.LambdaUtils;
import com.yc.util.SpiderHelper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

public class test {
    @Resource
    private ResourceAction resourceAction;
    @Resource
    private UserAction userAction;
    @Value("${web.upload-path}")
    private String path;

    @Test
    public void dateformat(){
        SimpleDateFormat simpleformat = new SimpleDateFormat("EEEE");
        String strDayofWeek = simpleformat.format(new Date());
        System.out.println("Day of Week = "+strDayofWeek);
        String[] weekDays = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六","星期日"};
        for ( int i = 0; i < weekDays.length; i++ ) {
            if ( weekDays[i].equals(strDayofWeek) ){
                System.out.println(i);
                break;
            }
        }
        simpleformat = new SimpleDateFormat("yyyy-MM-dd");
        strDayofWeek=simpleformat.format(new Date());
        System.out.println(strDayofWeek);
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)-1);
        System.out.println(DateUtil.TimeFormat(calendar.getTime()));
    }

    @Test
    public void time(){
        System.out.println(DateUtil.Format(new Date()));
    }

    @Test
    /**
     * 图片裁剪
     */
    public void contextLoads() {
        try {
            InputStream inputStream = new FileInputStream("D:\\1.png");
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            BufferedImage bf = new BufferedImage(600,300,BufferedImage.TYPE_INT_BGR);  //1000*300需要裁剪的大小
            bf.getGraphics().drawImage(bufferedImage,0,0,1000,300,null);

            FileOutputStream outImgStream = new FileOutputStream("D:\\cp01.png");
            ImageIO.write(bufferedImage, "jpg", outImgStream);   //直接存储到本地


            //暂时存储为字节流用于上传到服务器，我用的是ftp上传
            ByteArrayOutputStream baty = new ByteArrayOutputStream();
            ImageIO.write(bf,"jpg",baty);
            byte[]  buff =  baty.toByteArray();
            InputStream in =  new ByteArrayInputStream(buff); //存储为字节流，用于上传到服务器

            FileOutputStream fos = new FileOutputStream("d:\\aa.jpg");  //转换为字节流存储到本地的测试方法，证明转换成功

            byte[] b = new byte[1024];
            int length;
            while((length = in.read(b)) != -1 ){
                fos.write(b,0,length);
            }
            in.close();
            fos.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void sendmail(){
        User user=new User();
        user.setEmail("2889086043@qq.com");
        System.out.println(userAction.sendmail(user));
    }

    @Test
    public void deleteFile(){
        Integer uid=1;
        String path="D:/Project/IdeaProjects/Carttoon/Carttoon_index/src/main/resources/static/upload/image/";
        System.out.println("path:"+path);
        String str=path.replace("/","\\");
        System.out.println("str:"+str);
        Path paths = Paths.get(str+uid);
        System.out.println(paths.getParent()+":"+paths.getFileName());
        try {
            FileUtil.deleteFile(paths);
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    @Test
    public void test4(){
        String addr="https://www.scdmfun.cn/bangumi/sc69.html";
        try {
            Cartoon cartoon=SpiderHelper.getCartoon(addr);
            System.out.println(cartoon.getAlias());
            System.out.println(cartoon.getCname());
            System.out.println(cartoon.getCimage());
            System.out.println(cartoon.toString());
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭爬取播放地址时在控制台的js输出
     */
    static {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<ch.qos.logback.classic.Logger> loggerList = loggerContext.getLoggerList();
        loggerList.forEach(logger -> {
            logger.setLevel(Level.OFF);
        });
    }

    @Test
    public void test5(){
        List<String> newAddList=new ArrayList<>();//新增数据集合
        List<String> updateList=new ArrayList<>();//更新数据集合
        try {
//            Map map= SpiderHelper.getMap();
//            List cartoonList=(ArrayList)(map.get("cartoonList"));  //爬取的动漫资源集合
//            List<String> stringList=(ArrayList)map.get("stringList");  //爬取失败的动漫资源集合
//            Map<String, List <List< Map<String, String> >>> stringListMap=(HashMap)map.get("stringListMap"); //爬取的播放路线集合
//            ObjectMapper objectMapper = new ObjectMapper();
            String addr = "https://www.scdmfun.cn/map.html";
            URL url = new URL(addr);
            Document doc = Jsoup.parse(url, 10000);
            Elements elements = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li");
            List< Cartoon > cartoonList = new ArrayList<>();
            List< String > stringList = new ArrayList<>();
            Map< String, List < Pmap > > stringListMap = new HashMap<>();
            elements.forEach(LambdaUtils.consumerWithIndex((element, index) -> {
                System.out.println(element.select("li>a").attr("href"));
                String type = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li:nth-child(" + (index + 1) + ") > a > div.hl-item-div.hl-item-div2.hl-col-xs-20w.hl-col-sm-15w.hl-col-md-10w > div").text();
                System.out.println(type);
                if ( "涩涩".equals(type) || "哒咩涩涩".equals(type) ) {
                    System.out.println("获取失败");
                } else {
                    String add = element.select("li>a").attr("href");
                    try {
                        Cartoon cartoon = SpiderHelper.getCartoon("https://www.scdmfun.cn" + add);
                        cartoonList.add(cartoon);
                        System.out.println(cartoon);
                        List<Pmap> pmapList=SpiderHelper.getPlayAdress("https://www.scdmfun.cn" + add);
                        System.out.println(cartoon.getCname()+" : "+pmapList);
                        stringListMap.put(cartoon.getCname(), pmapList);
                    } catch ( Exception e ) {
                        System.out.println("获取失败：" + e.getMessage());
                        stringList.add(add);
                    }
                }
            }));
            stringListMap.forEach((cname,playaddress)->{
                System.out.println(cname+" : "+playaddress);
            });
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    @Test
    public void test6() throws IOException {
        String addr = "https://www.scdmfun.cn/map.html";
        URL url = new URL(addr);
        Document doc = Jsoup.parse(url, 10000);
        String str = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li:nth-child(1) > a").text();
        Elements elements = doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li");
        elements.forEach(LambdaUtils.consumerWithIndex((element, index) -> {
            String name= doc.select("#conch-content > div > div > div > div.container.hl-new-cont > div > ul > li:nth-child("+index+") > a").attr("href");
            System.out.println(name);
        }));
        System.out.println(str);
    }

    @Test
    public void test7(){
        IndexAction indexAction=new IndexAction();
        indexAction.spiderData();
    }
}
